

import { APIURL } from '@/common/config/const';
import { ChatMessages, Message, type InsightConfig, type QueryMessage, type RecommendQuestion, type StatusMessage, type TextMessage } from '@/common/models/chat-message'
import type { FetchEventSourceOptions, FetchEventSourceReturn } from '@/common/models/fetch-event-source';
import { sendSSE } from '@/common/services/sse-request';
import { getEventBus } from '@/common/services/chat-event-bus';

const { messageUpdateEventBus, questionUpdateEventBus, insightConfigEventBus } = getEventBus();

/**
 * 处理文本消息 （更新消息列表）
 * @param nMessage 新消息
 * @param sMessages 消息列表
 */
function detailTextMessage(newMessage: Message, chatMessage: ChatMessages) {
  const messages = chatMessage.messages;
  const existMessage = messages.find(message => message.id === newMessage.id);
  if (existMessage) {
    (existMessage.body as TextMessage).content = (newMessage.body as TextMessage).content;
  } else {
    messages.push(newMessage);
  }
}

/**
 * 处理RAG消息 （更新溯源列表）
 * @param nMessage 新消息
 * @param sMessages 消息列表
 */
function detailRAGMessage(newMessage: Message, chatMessage: ChatMessages) {
  const messages = chatMessage.messages;
  const existMessage = messages.find(message => message.id === newMessage.id);
  if (existMessage) {
    existMessage.body = newMessage.body;
  } else {
    messages.push(newMessage);
  }
}


/**
 * 
 * @param ev 流式消息内容
 * @param message 响应消息（回答）
 * @param askMessage 问句消息（请求）
 */
function messageHandler(ev: FetchEventSourceReturn, message: ChatMessages, askMessage: ChatMessages) {

  // 文本类型消息 RAG类型消息
  if (ev.event === 'TEXT' || ev.event === 'RAG_CONTENT') {
    detailTextMessage(ev.data, message);
    messageUpdateEventBus.emit({ id: message.id });
  }

  // RAG源地址类型消息
  if (ev.event === 'RAG_SOURCE') {
    detailRAGMessage(ev.data, message);
    messageUpdateEventBus.emit({ id: message.id });
  }

  // 可视化洞察类型消息
  if (ev.event === 'INSIGHT_CONFIG') {
    insightConfigEventBus.emit(ev.data.body as InsightConfig);
  }

  // 请求类型消息（首条消息，补全本地消息字段）
  if (ev.event === 'REQUEST') {
    message.id = ev.id;
    message.group_session_id = (ev.data.body as QueryMessage).group_session_id;
    askMessage.id = ev.id;
    askMessage.group_session_id = (ev.data.body as QueryMessage).group_session_id;
  }

  // 模块类型消息
  if (ev.event === 'SECTION') {
    message.messages.push(ev.data);
    messageUpdateEventBus.emit({ id: message.id });
  }

  // 模块类型消息
  if (ev.event === 'STATUS_CHANGE') {
    messageUpdateEventBus.emit({ id: message.id, status: (ev.data.body as StatusMessage) });
  }

  // 请求类型消息（首条消息，补全本地消息字段）
  if (ev.event === 'RECOMMEND') {
    questionUpdateEventBus.emit({ questions: (ev.data.body as RecommendQuestion).questions })
  }
}

/**
 * 关闭消息
 * @param message 消息
 */
function closeMessage(message: ChatMessages) {
  messageUpdateEventBus.emit({ id: message.id, status: { current: 'close', reason: '结束', description: '结束' } });
}

/**
 * 消息会话hook 用于流式消息请求和展示
 * @param queryMessage 问句消息
 */
export function useChatMessage(askMessage: ChatMessages) {

  // 创建消息实例 用于动态展示 扩展消息
  const message = new ChatMessages('ASSISTANT', []);

  // 问句消息
  const queryMessage = askMessage.messages[0].body as QueryMessage;

  const url = `${APIURL.getChatMessage}?code=${window.F10Utils.getUrlParams('code') || '300033'}&market=${window.F10Utils.getUrlParams('market') || '33'}&engine=${window.F10Utils.getUrlParams('engine') || 'default'}`;
  // SSE请求配置
  const options: FetchEventSourceOptions = {
    url,
    method: 'POST',
    data: queryMessage,
    onmessage: ev => messageHandler(ev, message, askMessage),
    onclose: () => closeMessage(message)
  }

  // 发送SSE请求 并返回控制器（用于中断请求）
  const { controller, request } = sendSSE(options);

  return {
    message,
    controller,
    request
  }
} 